"use client";
/* eslint-disable react-hooks/rules-of-hooks */
import React, { useState, useRef, useEffect } from 'react';
import { RiRobot2Line } from "react-icons/ri";
import { LiaUserFriendsSolid } from "react-icons/lia";
import { TiMessages } from "react-icons/ti";
import { LuArrowLeftToLine } from "react-icons/lu";
import ChatMessageBubble from '@/components/ChatMessageBubble';
import { useSelector } from 'react-redux';
import { getDateTime, getDateOnly } from '@/lib/getNowTime';
import ChatMessageList from '@/components/ChatMessageList';

type ChatRecord = {
    type: "start" | "end",
    message: string;
    url?: string;
    topMessage?: string;

};

const page = () => {
    const [selectedOption, setSelectedOption] = useState('Radio1');
    const [userInput, setUserInput] = useState('');
    const [chatrecords, setChatrecords] = useState<ChatRecord[]>([]);
    const scrollContainerRef = useRef<HTMLDivElement>(null);
    const username = useSelector((state: any) => state.username);


    const handleSubmitMessage = async (e: React.ChangeEvent<HTMLFormElement>) => {
        e.preventDefault();
        if (userInput === '') return;
        setChatrecords([...chatrecords, { type: 'end', message: userInput }]);
        console.log(chatrecords);
        setChatrecords((prevchatrecords) => [...prevchatrecords, { type: 'start', topMessage: "Ai机器人", url: "/robotpic.webp", message: '正在思考中...' }]);

        await fetchPost({ message: userInput }).then((response) => {

            if (response) {
                setChatrecords((prevchatrecords) => prevchatrecords.slice(0, prevchatrecords.length - 1));

                setChatrecords((prevchatrecords) => [...prevchatrecords, { type: 'start', topMessage: "Ai机器人", url: "/robotpic.webp", message: response.AichatReplyMessage }]);


            }
        });
        setUserInput("");
        console.log(chatrecords);

    };

    const fetchPost = async (data: object) => {
        try {
            const response = await fetch("http://localhost:3000/api/aichat", {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(data)
            });

            const result = await response.json();
            return result;
        } catch (error) {
            console.error('Error:', error);
            return null;
        }
    };

    useEffect(() => {
        if (scrollContainerRef.current) {
            scrollContainerRef.current.scrollTop = scrollContainerRef.current.scrollHeight;
        }
    }, [chatrecords]);

    return (
        <div className='flex justify-center bg-blue-50 pt-2 h-[calc(95vh-65px)]'>
            {!username &&
                <div className='z-10 fixed flex justify-center items-center bg-black/50 w-full h-full text-2xl'>
                    <p className='bg-amber-300 shadow-2xl p-10 rounded-2xl max-w-[300px] font-douyin'>请登录后使用</p>
                </div>}
            {/* 这是侧边栏 */}
            <div className='flex flex-col space-x-5 bg-[#2E2E2E] rounded-l-lg w-14 text-3xl'>

                <label htmlFor="robot" className='text-[#868686] has-checked:text-[#07BE5E]'>
                    <RiRobot2Line role='button' className='inline mt-5 ml-3 hover:text-[#07BE5E] hover:cursor-pointer' />
                    <input type="radio" id="robot" name="sidebar" className='hidden' checked={selectedOption === 'Radio1'} onChange={() => setSelectedOption('Radio1')} />
                </label>
                <label htmlFor="message" className='text-[#868686] has-checked:text-[#07BE5E]'>
                    <TiMessages className='mt-5 ml-3 hover:text-[#07BE5E] hover:cursor-pointer' />
                    <input type="radio" id="message" name="sidebar" className='hidden' checked={selectedOption === 'Radio2'} onChange={() => setSelectedOption('Radio2')} />
                </label>
                <label htmlFor="friend" className='text-[#868686] has-checked:text-[#07BE5E]'>
                    <LiaUserFriendsSolid className='mt-5 ml-3 hover:text-[#07BE5E] hover:cursor-pointer' />
                    <input type="radio" id="friend" name="sidebar" className='hidden' checked={selectedOption === 'Radio3'} onChange={() => setSelectedOption('Radio3')} />
                </label>

            </div>
            {/* 这是好友和消息栏 */}
            <div className='bg-[#F7F7F7] border border-[#D6D6D6] w-4/12 min-w-[200px]'>
                {/* 这是搜索栏 */}
                <div className='flex justify-around items-center space-x-3 p-3 border-[#D6D6D6] border-b w-full h-[56px]'>
                    <label className="flex bg-[#E2E2E2] has-focus-within:bg-white p-1 rounded-sm has-focus-within:outline-[#E2E2E2] has-focus-within:outline-1 w-full min-w-[65%]">
                        <p className='mx-1 text-ms'>🔍</p>
                        <input placeholder='搜索' className='outline-0' />
                    </label>
                    <button className='text-xl btn btn-sm'>+</button>
                </div>
                {/* 这是聊天卡片容器 */}
                <div className='flex flex-col w-full max-h-[calc(95vh-65px-56px-8px-0.8px)] overflow-y-auto'>
                    {/* 这是聊天小卡片 */}
                    <ChatMessageList picurl='/robotpic.webp' chatUserName='Ai机器人' lastChatMessage='你好，我是ai机器人，很高兴为你服务!' lastChatDate={getDateOnly} />
                    <ChatMessageList chatUserName='李东' lastChatDate='1970/01/01' lastChatMessage='最近一次的聊天内容' />



                </div>
            </div>
            {/* 这是主要聊天区域 */}
            <div className='bg-[#F5F5F5] border border-[#D6D6D6] rounded-r-lg w-5/10'>
                {/* 背景 */}
                <div className='flex flex-col'>
                    <header className='flex justify-between items-center p-3 border-[#D6D6D6] border-b h-[56px]'>
                        {/* 折叠消息框 */}
                        <LuArrowLeftToLine className='' />
                        <p>Ai机器人</p>
                        <button className='btn btn-ghost'>x</button>

                    </header>
                    {/* 这里是聊天框 */}
                    <div className='flex flex-col h-[calc(95vh-65px-56px-8px-0.8px-150px)] overflow-y-scroll' ref={scrollContainerRef}>
                        {/* 这是聊天气泡 */}
                        <ChatMessageBubble type='start' messageTime={getDateTime} topMessage=" Ai机器人" messageBody='你好，我是ai机器人，很高兴为你服务!' imgUrl='/robotpic.webp' />

                        {chatrecords.map((record, index) => <ChatMessageBubble key={index} type={record.type} messageTime={(new Date()).toLocaleDateString() + " " + (new Date()).toLocaleTimeString()} messageBody={record.message} imgUrl={record.url} topMessage={record.topMessage} />)}


                    </div>
                    {/* 这是输入框 */}
                    <form onSubmit={handleSubmitMessage} className='border-[#D6D6D6] border-t h-[150px]'>
                        <textarea className='w-full h-[105px] resize-none' onChange={(e) => setUserInput(e.target.value)} name="" id="" value={userInput}></textarea>
                        <button type='submit' className='mx-2 btn btn-sm btn-success'>发送</button>
                    </form>

                </div>

            </div >
        </div>
    );
};

export default page;
